package cn.edu.sjtu.se.dslab.component.data.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import cn.edu.sjtu.se.dslab.component.data.DataAttribute;
import cn.edu.sjtu.se.dslab.component.data.DataType;
import cn.edu.sjtu.se.dslab.util.Const;

public class DataTypeUtil {
	public String getDataTypeCode(DataType dataType) {
		if (dataType.getCategory().endsWith(Const.DATA_TYPE_BASIC)) {
			return dataType.getName();
		} else if (dataType.getCategory().endsWith(Const.DATA_TYPE_ENUM)) {
			StringBuffer codeBuffer = new StringBuffer();
			codeBuffer.append("typedef enum{\n\t");
			String[] enums = dataType.getEnumList().split(";");
			for (int i = 0; i < enums.length; i++) {
				if (!enums[i].equals(";") && !enums[i].equals("")) {
					if (i != 0) {
						codeBuffer.append(',');
					}
					codeBuffer.append(enums[i]);
				}
			}
			codeBuffer.append("\n}" + dataType.getName() + ";");
			return codeBuffer.toString();

		} else if (dataType.getCategory().endsWith(Const.DATA_TYPE_STRUCT)) {
			StringBuffer codeBuffer = new StringBuffer();
			codeBuffer.append("typedef struct{\n\t");
			Set<DataAttribute> attributes = dataType.getAttributes();
			List<DataAttribute> attrList = new ArrayList<DataAttribute>(
					attributes);
			DataAttributeComparator comparator = new DataAttributeComparator();
			Collections.sort(attrList, comparator);
			for (DataAttribute dataAttribute : attrList) {
				if (dataAttribute.getLength() == 0) {
					codeBuffer.append(dataAttribute.getType().getName() + "  "
							+ dataAttribute.getName() + ";\n\t");
				} else {
					codeBuffer.append(dataAttribute.getType().getName() + "  "
							+ dataAttribute.getName() + ": "
							+ dataAttribute.getLength() + ";\n\t");
				}

			}
			codeBuffer.append("}" + dataType.getName() + ";");
			return codeBuffer.toString();
		}
		return "";
	}
}
